﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EFMassOperations
{
	class Cache<TVar, TKey,TStore>
	{
		Func<TVar, TKey> keyExtractor;
		Func<TVar, TKey, TStore> getObject;
		Dictionary<TKey, TStore> cache = new Dictionary<TKey, TStore>();

		public Cache(Func<TVar, TKey> keyExtractor, Func<TVar, TKey, TStore> getObject)
		{
			this.keyExtractor = keyExtractor;
			this.getObject = getObject;
		}

		public TStore this[TVar index]
		{
			get
			{
				TKey key = keyExtractor(index);
				if (cache.ContainsKey(key))
					return cache[key];
				TStore value = getObject(index, key);
				cache.Add(key, value);
				return value;
			}
			private set { }
		}
	}
}
